﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using PhoneStore.Presentation.CompositeControl;
using PhoneStore.Entity;
using PhoneStore.Presentation.Util;

namespace PhoneStore.Presentation
{
    /// <summary>
    /// Interaction logic for SellProduct.xaml
    /// </summary>
    public partial class SellProduct : WindowBase
    {
        public SellProduct(Staff currentStaff)
        {
            InitializeComponent();
            CurrentStaff = currentStaff;
            ucPhoneList.SetUpScreenMode(ScreenMode.Sell);
            ucAccessoryList.SetUpScreenMode(ScreenMode.Sell);
            ucAccessoryList.ShoppingCart = ucPhoneList.ShoppingCart =
                ShoppingCart = new List<SellProductDetail>();
            gbCusInfo.Visibility = Visibility.Collapsed;
            this.Closing += new System.ComponentModel.CancelEventHandler(SellProduct_Closing);
        }

        public Staff CurrentStaff { get; set; }

        void SellProduct_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Welcome w = new Welcome();
            w.Show();
        }

        private void tabCheckOut_GotFocus(object sender, RoutedEventArgs e)
        {

        }

        private List<SellProductDetail> ShoppingCart { get; set; }

        private void tcTabs_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.OriginalSource == tcTabs)
            {
                if (tabCheckOut.IsSelected)
                {
                    RefreshGrid();
                }
            }
        }

        protected Customer Cust { get; set; }

        public string CusName { get; set; }
        public string CusKind { get; set; }

        private void btnAddCus_Click(object sender, RoutedEventArgs e)
        {
            MessageTextbox tb = new MessageTextbox();
            tb.LabelText = "Nhập Mã Khách Hàng";
            tb.ShowDialog();
            if (tb.IsOk)
            {
                var cus = DAO.Single<Customer>(x => x.PersonID == tb.ReturnValue, "Kind");
                if (cus == null)
                {
                    MessageBox.Show("Khách hàng không tồn tại");
                }
                Cust = cus;
                SetUpCustomer(cus);
            }
        }

        private void SetUpCustomer(Customer cus)
        {
            if (cus != null)
            {
                gbCusInfo.Visibility = Visibility.Visible;
                gbCusInfo.DataContext = cus;
                CusName = cus.Fullname;
                CusKind = cus.Kind.Description;
                Rate = cus.Kind.rate.Value;
                CustomerName = cus.Fullname;
            }
            else
            {                
                gbCusInfo.Visibility = Visibility.Collapsed;
                CusName = null;
                CusKind = null;
                Rate = 0;
            }
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            var selectedItem = dgCart.SelectedItem as SellProductDetail;
            if (selectedItem != null)
            {
                ShoppingCart.Remove(selectedItem);
                RefreshGrid();
            }
        }

        private void RefreshGrid()
        {
            dgCart.ItemsSource = null;
            dgCart.ItemsSource = ShoppingCart;
            double seed = 0;
            lblTotalCost.Content = TotalCost = ShoppingCart.Aggregate(seed, (preSeed, x) => x.Cost + preSeed);
            lblActualCost.Content = ActualCost;
            lblDischarge.Content = DisCharge;
            btnDelete.IsEnabled = false;
        }

        public string CustomerName { get; set; }
        private double _Rate;
        public double Rate
        {
            get
            {
                return _Rate;
            }
            set
            {
                _Rate = value;
                lblActualCost.Content = ActualCost;
                lblDischarge.Content = DisCharge;
            }
        }
        public double TotalCost { get; set; }
        public double DisCharge
        {
            get
            {
                return TotalCost * _Rate / 100;
            }
        }
        public double ActualCost
        {
            get
            {
                return TotalCost - DisCharge;
            }
        }

        private void dgCart_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.OriginalSource == dgCart)
            {
                if (dgCart.SelectedItem != null)
                {
                    btnDelete.IsEnabled = true;
                }
                else
                {
                    btnDelete.IsEnabled = false;
                }
            }
        }

        private void btnSell_Click(object sender, RoutedEventArgs e)
        {
            Bill bill = new Bill
            {
                SellDate = DateTime.Now,
                StaffID = CurrentStaff.ID
            };
            if (Cust != null)
            {
                bill.CustomerID = Cust.PersonID;
            }
            DAO.Add(bill);

            foreach (var p in ShoppingCart)
            {
                var prod = DAO.Single<Product>(x => x.ProductID == p.ProductID);
                prod.Quantity -= p.Quantity;
                DAO.Update(prod);
                DAO.Add(new BillDetail()
                {
                    BillID = bill.BillID,
                    Amount = p.Quantity,
                    Price = prod.Price,
                    ProductID = p.ProductID                    
                });
            }

            BillReportWrapperModel model = new BillReportWrapperModel()
            {
                ActualCost = ActualCost.ToString(),
                Cost = TotalCost.ToString(),
                CusKind = CusKind != null ? CusKind : "______",
                CusName = CusName != null ? CusName : "______",
                Discharge = DisCharge.ToString(),
                list = ShoppingCart,
                Rate = Rate.ToString()
            };
            BillGenerator b = new BillGenerator();
            b.source = model;
            b.Show();
            ShoppingCart.Clear();
            RefreshGrid();
            SetUpCustomer(null);
        }
    }
}
